package com.integral.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@ConditionalOnProperty(value = {"path.excelBasePath"}, matchIfMissing = false)

public class ExcelHelper {

    private static String excelBasePath ="/var";


    private static final Logger logger = LoggerFactory.getLogger(ExcelHelper.class);

    @Value("${path.excelBasePath}")
    public void setExcelBasePath(String excelBasePath) {
        ExcelHelper.excelBasePath = excelBasePath;
    }

    public static String generateTemplate(Class clz, String funName) {
        String fileName = "TPL_" + funName + "_" + DateUtils.format(new Date(),"yyyyMMdd") + "_" + RandomStringUtils.randomAlphanumeric(4)  +".xlsx";
        File file = new File(excelBasePath + File.separator + fileName);
        try {
            ExportParams params = new ExportParams(null, null, "模板");
            params.setType(ExcelType.XSSF);
            Workbook workbook = ExcelExportUtil.exportExcel(params, clz, new ArrayList());
            FileOutputStream fos = new FileOutputStream(file);
            workbook.write(fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public static <T> String generateExportFile(List<T> dataList, String funName) {
        if(null == dataList){
            return null;
        }
        Class clz = dataList.get(0).getClass();
        ExportParams params = new ExportParams(null, null, "数据列表");
        params.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, clz, dataList);
        String fileName = "DATA_" + funName + "_" + DateUtils.format(new Date(),"yyyyMMdd") + "_" + RandomStringUtils.randomAlphanumeric(4) +".xlsx";
        File file = new File(excelBasePath + File.separator + fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            workbook.write(fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    // 上边的方法 dataList 如果是空数组会报错
    public static <T> String generateExportFile(List<T> dataList, String funName, Class clz) {
        if(null == dataList){
            return null;
        }
        if (null == clz && dataList.size() > 0){
            clz = dataList.get(0).getClass();
        }
        ExportParams params = new ExportParams(null, null, "数据列表");
        params.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, clz, dataList);
        String fileName = "DATA_" + funName + "_" + DateUtils.format(new Date(),"yyyyMMdd") + "_" + RandomStringUtils.randomAlphanumeric(4) +".xlsx";
        File file = new File(excelBasePath + File.separator + fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            workbook.write(fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public static <T> List<T> parseUploadData(MultipartFile tempUploadFile, Class<T> clz) {
        try {
            InputStream is = tempUploadFile.getInputStream();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            List<T> list = ExcelImportUtil.importExcel(is,clz, params);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void downloadExcelFile(HttpServletRequest request, HttpServletResponse response, String fileName){
        BufferedInputStream bis = null;
        try {
            File file = new File(excelBasePath + File.separator + fileName);
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] data = new byte[(int)(file.length())];
            bis.read(data, 0, data.length);

            response.reset();
            response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.addHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Content-Disposition", "attachment; filename=\""+ fileName +"\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");

            IOUtils.write(data, response.getOutputStream());

        } catch (Exception e){
            logger.error("下载文件异常：", e);
        } finally {
            try{
                bis.close();
            }catch (Exception e){
            }
        }
    }
}
